/**
 * 处理视图层逻辑
 */
import { gameCol, gameRow } from './config.js'

// init map
export function initMap (map) {
  for (let i = 0; i < gameRow; i++) {
    map[i] = []
    for (let j = 0; j < gameCol; j++) {
      map[i][j] = 0
    }
  }
}

export function addBoxToMap (box, map) {
  const matrix = box.shape
  const row = matrix.length
  const col = matrix[0].length
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      const x = box.x + j
      const y = box.y + i
      if (matrix[i][j]) {
        map[y][x] = -1
      }
    }
  }
}

export function eliminate (map) {
// 1. 需要获取满行的索引
  const lines = getCanEliminateLines(map)

  // 2. 删除满行的  在头部添加新行
  _eliminate(lines, map)
}
function _eliminate (lines, map) {
  const col = map[0].length
  lines.forEach(line => {
    map.splice(line, 1)
    map.unshift(new Array(col).fill(0))
  })
}
function getCanEliminateLines (map) {
  return map.reduce((r, row, index) => {
    const status = row.every((v) => {
      return v === -1
    })
    if (status) {
      r.push(index)
    }
    return r
  }, [])
}
